package com.gcit.seniorWish.web.modular.examinee.service.impl;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.gcit.seniorWish.core.cache.CacheKit;
import com.gcit.seniorWish.web.common.constant.cache.Cache;
import com.gcit.seniorWish.web.common.constant.cache.CacheKey;
import com.gcit.seniorWish.web.common.constant.factory.ConstantFactory;
import com.gcit.seniorWish.web.common.persistence.model.*;
import com.gcit.seniorWish.web.core.shiro.ShiroKit;
import com.gcit.seniorWish.web.common.constant.Const;
import com.gcit.seniorWish.web.common.constant.enums.ExamineeStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.ManagerStatusEnum;
import com.gcit.seniorWish.web.common.constant.enums.RoleEnum;
import com.gcit.seniorWish.web.common.constant.enums.UserTypeEnum;
import com.gcit.seniorWish.web.common.persistence.dao.SeniorExamineeMapper;
import com.gcit.seniorWish.web.modular.examinee.dao.SeniorExamineeDao;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorExamineeService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolClassService;
import com.gcit.seniorWish.web.modular.examinee.service.ISeniorSchoolService;
import com.gcit.seniorWish.web.modular.examinee.transfer.ExamineeDto;
import com.gcit.seniorWish.web.modular.system.service.IRoleService;
import com.gcit.seniorWish.web.modular.system.service.IUserMgrService;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 中考考生信息表 服务实现类
 * </p>
 *
 * @author tonglu
 * @since 2018-03-20
 */
@Service
public class SeniorExamineeServiceImpl extends ServiceImpl<SeniorExamineeMapper, SeniorExaminee>
		implements ISeniorExamineeService {

	@Autowired
	private ISeniorSchoolClassService seniorSchoolClassService;

	@Autowired
	ISeniorSchoolService seniorSchoolService;

	@Autowired
	private IUserMgrService userMgrService;

	@Resource
	SeniorExamineeDao seniorExamineeDao;

	@Autowired
	IRoleService roleService;

	/**
	 * 通过excel导入考生信息
	 *
	 * @param inputStream 输入流
	 * @author tonglu
	 * @date 2018-03-21
	 */
	@SuppressWarnings({"rawtypes", "unchecked"})
	@Override
	@Transactional
	public String importExaminee(InputStream inputStream) {
		StringBuffer msg = new StringBuffer();
		ExcelReader reader = ExcelUtil.getReader(inputStream);
		Map<String, String> headerAlias = new HashMap<String, String>();
		headerAlias.put("学校名称", "schoolName");
		headerAlias.put("学校代号", "schoolCode");
		headerAlias.put("班级名称", "senoirClassName");
		headerAlias.put("班级代号", "seniorClassCode");
		headerAlias.put("准考证号", "examCardNumber");
		headerAlias.put("考生姓名", "studentName");
		headerAlias.put("性别", "gender");
		headerAlias.put("身份证号码", "idCard");
		headerAlias.put("联系电话1", "phone1");
		headerAlias.put("联系电话2", "phone2");
		headerAlias.put("考场号", "examSiteNumber");
		headerAlias.put("座位号", "seatNumber");
		headerAlias.put("民族", "nation");
		headerAlias.put("籍贯", "nativePlace");
		headerAlias.put("政治面貌", "politicalName");
		headerAlias.put("考生类型名称", "studentTypeName");
		headerAlias.put("户籍地区代码", "residenceAreaCode");
		headerAlias.put("户籍地址", "residenceAddress");
		headerAlias.put("学籍号", "studentNumber");
		headerAlias.put("建档号", "archivesNumber");
		headerAlias.put("出生年月", "birthday");
		reader.setHeaderAlias(headerAlias);
		HashMap<String, Integer> map = new HashMap<String, Integer>();// 判断同一个Excel中是否存在相同的准考证号
		List<ExamineeDto> excelData = reader.readAll(ExamineeDto.class);
		if (excelData.size() > 0) {
			Iterator excelIt = excelData.iterator();
			ExamineeDto item = null;
			int i = 0;
			// 循环列表中的记录
			while (excelIt.hasNext()) {
				i++;
				item = (ExamineeDto) excelIt.next();
				// 判断必填内容是否填写
				if (StrUtil.isBlank(item.getSchoolName())) {
					msg.append("第" + i + "条缺少学校名称\n");
					continue;
				}
				if (StrUtil.isBlank(item.getSchoolCode())) {
					msg.append("第" + i + "条缺少学校代号\n");
					continue;
				}
				if (StrUtil.isBlank(item.getSenoirClassName())) {
					msg.append("第" + i + "条缺少班级名称\n");
					continue;
				}
				if (StrUtil.isBlank(item.getSeniorClassCode())) {
					msg.append("第" + i + "条缺少班级代号\n");
					continue;
				}
				if (StrUtil.isBlank(item.getExamCardNumber())) {
					msg.append("第" + i + "条缺少准考证号\n");
					continue;
				} else {
					Integer line = map.get(item.getExamCardNumber());
					if (line == null) {
						map.put(item.getExamCardNumber(), i);
						if (this.selectCount(Condition.create().eq("exam_card_number", item.getExamCardNumber())) > 0) {// 该准考证号已存在
							msg.append("第" + i + "条准考证号已存在\n");
							continue;
						}
						// 判断账号是否重复
						if (userMgrService
								.selectCount(Condition.create().eq("account", item.getExamCardNumber())) > 0) {
							msg.append("第" + i + "条准考证号生成的用户已存在\n");
							continue;
						}
					} else {
						msg.append("第" + i + "条准考证号与第" + line + "条准考证号重复\n");
						continue;
					}
				}
				if (StrUtil.isBlank(item.getStudentName())) {
					msg.append("第" + i + "条缺少考生姓名\n");
					continue;
				}
				if (StrUtil.isBlank(item.getIdCard())) {
					msg.append("第" + i + "条缺少身份证号码\n");
					continue;
				} else {
				/*	if (!IdcardUtil.isValidCard(item.getIdCard())) {
						msg.append("第" + i + "条身份证号码错误\n");
						continue;
					}*/
				}
				if (StrUtil.isBlank(item.getArchivesNumber())) {
					msg.append("第" + i + "条缺少建档号\n");
					continue;
				}
				if (item.getBirthday()==null) {
					msg.append("第" + i + "条缺少建档号\n");
					continue;
				}
			}
			if (StrUtil.isBlank(msg.toString())) {
				// 数据保存
				for (ExamineeDto et : excelData) {
					SeniorSchool seniorSchool = new SeniorSchool();// 学校
					SeniorSchoolClass schoolClass = new SeniorSchoolClass();// 班级
					SeniorExaminee examinee = new SeniorExaminee();// 考生
					if (seniorSchoolService.selectCount(Condition.create().eq("school_code", et.getSchoolCode())) > 0) {// 学校存在获取数据
						seniorSchool = seniorSchoolService
								.selectOne(Condition.create().eq("school_code", et.getSchoolCode()));
					} else {// 该学校不存在
						seniorSchool.setSchoolCode(et.getSchoolCode());
						seniorSchool.setSchoolName(et.getSchoolName());
						seniorSchoolService.insert(seniorSchool);
						// 插入用户表信息
						User user = new User();
						user.setType(UserTypeEnum.SCHOOL.getValue());
						user.setAccount("szwz" + seniorSchool.getSchoolCode());
						user.setName(seniorSchool.getSchoolName());
						user.setSchoolId(seniorSchool.getId());
						// 完善账号信息
						user.setSalt(ShiroKit.getRandomSalt(5));
						user.setPassword(ShiroKit.md5(Const.SCHOOLORCLASS_PWD, user.getSalt()));
						user.setDeptId(Const.DEFAULT_DEPT_ID);
						user.setStatus(ManagerStatusEnum.ABLE.getCode());
						userMgrService.insert(user);
						Role role = roleService
								.selectOne(Condition.create().eq("name", RoleEnum.SCHOOL_ADMIN.getDes()));
						userMgrService.setRoles(user.getId(), role.getId());
					}
					if (seniorSchoolClassService
							.selectCount(Condition.create().eq("senoir_school_id", seniorSchool.getId())
									.eq("senior_class_code", et.getSeniorClassCode())) > 0) {// 该学校此班级代号已存在
						schoolClass = seniorSchoolClassService
								.selectOne(Condition.create().eq("senoir_school_id", seniorSchool.getId())
										.eq("senior_class_code", et.getSeniorClassCode()));
					} else {// 该学校此班级不存在
						schoolClass.setSenoirSchoolId(seniorSchool.getId());
						schoolClass.setSeniorClassCode(et.getSeniorClassCode());
						schoolClass.setSenoirClassName(et.getSenoirClassName());
						seniorSchoolClassService.insert(schoolClass);
						// 插入用户表信息
						User user = new User();
						user.setType(UserTypeEnum.TEACHING.getValue());
						user.setAccount("szwz" + seniorSchool.getSchoolCode() + schoolClass.getSeniorClassCode());
						user.setName(schoolClass.getSenoirClassName());
						// 完善账号信息
						user.setSalt(ShiroKit.getRandomSalt(5));
						user.setPassword(ShiroKit.md5(Const.SCHOOLORCLASS_PWD, user.getSalt()));
						user.setDeptId(Const.DEFAULT_DEPT_ID);
						user.setStatus(ManagerStatusEnum.ABLE.getCode());
						user.setSchoolId(seniorSchool.getId());
						user.setClassId(schoolClass.getId());
						userMgrService.insert(user);
						Role role = roleService
								.selectOne(Condition.create().eq("name", RoleEnum.CLASS_TEACHER.getDes()));
						userMgrService.setRoles(user.getId(), role.getId());
					}
					examinee.setExamCardNumber(et.getExamCardNumber());
					examinee.setStudentName(et.getStudentName());
					examinee.setGender(et.getGender());
					examinee.setIdCard(et.getIdCard());
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
					Date birth = null;
					try {
						birth = sdf.parse(sdf.format(et.getBirthday()));
					} catch (ParseException e) {
						e.printStackTrace();
					}
					if (birth != null)
						examinee.setBirthday(birth);
					examinee.setPhone1(et.getPhone1());
					examinee.setSeniorSchoolId(seniorSchool.getId());
					examinee.setSeniorClassId(schoolClass.getId());
					examinee.setWriteStatus(ExamineeStatusEnum.NOT_YET_WRITE.getValue());
					examinee.setConfirmStatus(ExamineeStatusEnum.NOT_YET_CONFIRM.getValue());
					examinee.setIsAbandoned(ExamineeStatusEnum.NOT_YET_ABANDON.getValue());
					examinee.setPhone2(et.getPhone2());
					examinee.setExamSiteNumber(et.getExamSiteNumber());
					examinee.setSeatNumber(et.getSeatNumber());
					examinee.setNation(et.getNation());
					examinee.setNativePlace(et.getNativePlace());
					examinee.setPoliticalName(et.getPoliticalName());
					examinee.setStudentTypeName(et.getStudentTypeName());
					examinee.setResidenceAreaCode(et.getResidenceAreaCode());
					examinee.setResidenceAddress(et.getResidenceAddress());
					examinee.setStudentNumber(et.getStudentNumber());
					examinee.setArchivesNumber(et.getArchivesNumber());
					examinee.setHeaderPath(et.getHeaderPath());
					this.insert(examinee);
					// 插入用户表信息
					User user = new User();
					user.setType(UserTypeEnum.EXAMINEE.getValue());
					user.setAccount(et.getExamCardNumber());
					user.setName(et.getStudentName());
					user.setSchoolId(seniorSchool.getId());
					user.setClassId(schoolClass.getId());
					// 完善账号信息
					user.setSalt(ShiroKit.getRandomSalt(5));
					user.setPassword(ShiroKit.md5(sdf.format(et.getBirthday()), user.getSalt()));
					user.setDeptId(Const.DEFAULT_DEPT_ID);
					user.setStatus(ManagerStatusEnum.ABLE.getCode());
					this.userMgrService.insert(user);
					Role role = roleService.selectOne(Condition.create().eq("name", RoleEnum.STUDENT.getDes()));
					userMgrService.setRoles(user.getId(), role.getId());
				}
			}
		} else {
			msg.append("导入模板为空\n");
		}
		return msg.toString();
	}

	@Override
	public List<Map<String, Object>> getExaminees(Pagination page, String seniorSchoolId, String seniorClassId,
												  String examCardNumber, String confirmStatus) {
		return seniorExamineeDao.getExaminees(page, seniorSchoolId, seniorClassId, examCardNumber, confirmStatus);
	}

	/**
	 * 根据学生准考证号查询学生信息 由于高使用率，做成缓存使用
	 *
	 * @param examCardNumber 考生准考证号
	 * @author gaozhichang
	 * @date 2018-03-25 上午 9:40
	 */
	@Override
	public SeniorExaminee getExamineeByExamCardNumber(String examCardNumber) {
		//由于该方法在同类中调用。无法使用基于aop的cacheable注解。手动使用缓存
		SeniorExaminee examinee= CacheKit.get(Cache.BUSS,CacheKey.EXAMINEE_INFO_BY_EXAM_CARD+examCardNumber);
		if(examinee==null){
			examinee = this.selectOne(Condition.create().eq("exam_card_number", examCardNumber));
			CacheKit.put(Cache.BUSS,"'"+CacheKey.EXAMINEE_INFO_BY_EXAM_CARD+"'"+examCardNumber,examinee);
		}
		return examinee;
	}

	/**
	 * 根据学生准考证号查询学生信息（包含学校班级信息） 由于学校班级信息可能会被其他方法修改，不可以直接缓存到学生信息中
	 *
	 * @param examCardNumber 考生准考证号
	 * @author gaozhichang
	 * @date 2018-03-25 上午 9:40
	 */
	@Override
	public SeniorExaminee getExamineeByExamCardNumberWithSchoolClassName(String examCardNumber) {
		SeniorExaminee examinee = this.getExamineeByExamCardNumber(examCardNumber);
		if(examinee==null){
			return null;
		}
		examinee.setSeniorSchoolName(
				ConstantFactory.me().getSeniorSchoolById(examinee.getSeniorSchoolId()).getSchoolName());
		examinee.setSeniorClassName(
				ConstantFactory.me().getSeniorSchoolClassById(examinee.getSeniorClassId()).getSenoirClassName());
		return examinee;
	}

	/**
	 * 更新考生信息
	 *
	 * @param examinee 考生信息
	 * @author gaozhichang
	 * @date 2018-03-26 下午 4:23
	 */
	@Override
	@Transactional
	@CacheEvict(value = Cache.BUSS, key = "'" + CacheKey.EXAMINEE_INFO_BY_EXAM_CARD + "'+#examinee.examCardNumber")
	public int updateExaminee(SeniorExaminee examinee) {
		return baseMapper.updateById(examinee);
	}

	/**
	 * 合并考生信息
	 *
	 * @param examinee 考生信息
	 * @author gaozhichang
	 * @date 2018-03-29 上午 9:49
	 */
	@Override
	@Transactional
	@CacheEvict(value = Cache.BUSS, key = "'" + CacheKey.EXAMINEE_INFO_BY_EXAM_CARD + "'+#examinee.examCardNumber")
	public void mergeExaminee(SeniorExaminee examinee) {
		// 当id为空时，新增考生
		if (StrUtil.isBlank(examinee.getId())) {
			// 插入考生表，初始化相关的状态
			examinee.setWriteStatus(ExamineeStatusEnum.NOT_YET_WRITE.getValue());
			examinee.setConfirmStatus(ExamineeStatusEnum.NOT_YET_CONFIRM.getValue());
			examinee.setIsAbandoned(ExamineeStatusEnum.NOT_YET_ABANDON.getValue());
			baseMapper.insert(examinee);
			// 在用户表插入对应的用户信息
			User user = new User();
			user.setType(UserTypeEnum.EXAMINEE.getValue());
			user.setAccount(examinee.getExamCardNumber());
			user.setName(examinee.getStudentName());
			user.setSchoolId(examinee.getSeniorSchoolId());
			user.setClassId(examinee.getSeniorClassId());
			// 完善账号信息
			user.setSalt(ShiroKit.getRandomSalt(5));
			user.setPassword(ShiroKit.md5(IdcardUtil.getBirthByIdCard(examinee.getIdCard()), user.getSalt()));
			user.setDeptId(Const.DEFAULT_DEPT_ID);
			user.setStatus(ManagerStatusEnum.ABLE.getCode());
			userMgrService.insert(user);
			Role role = roleService.selectOne(Condition.create().eq("name", RoleEnum.STUDENT.getDes()));
			userMgrService.setRoles(user.getId(), role.getId());
			// 当id不为空时，修改考生
		} else {
			List<SeniorExaminee> existExamineeList = baseMapper
					.selectList(Condition.create().setSqlSelect("exam_card_number").eq("id", examinee.getId()));
			// 当修改的用户存在并且准考证号修改了，需要修改对应user
			if (existExamineeList.size() > 0) {
				// 查询考生相对的用户表中的用户记录
				User user = userMgrService.selectOne(Condition.create().setSqlSelect("id").eq("account",
						existExamineeList.get(0).getExamCardNumber()));
				if (user != null) {
					user.setAccount(examinee.getExamCardNumber());
					user.setName(examinee.getStudentName());
					user.setClassId(examinee.getSeniorClassId());
					user.setSchoolId(examinee.getSeniorSchoolId());
					userMgrService.updateById(user);
				}
			}
			this.baseMapper.updateById(examinee);
		}
	}
	/**
	 * 获取导出考生信息列表（志愿信息）
	 *
	 * @author cuiyushu
	 * @date 2018-03-28 下午14:16
	 */

	// public List<SeniorExaminee> exportSeniorExamineeWithSeniorWish() {
	// List<SeniorExaminee> examineeList =
	// seniorExamineeDao.listSeniorExamineeExport();
	// return examineeList;
	// }

	/**
	 * 导出志愿信息
	 *
	 * @throw IOException
	 * @author cuiyuhsu
	 * @date 2018-03-28 下午14:40
	 */
	@Override
	public void exportExaminee(HttpServletResponse response, String seniorSchoolId, String seniorClassId,
							   String examCardNumber, Integer confirmStatus) throws IOException {
		// 获取列表
		List<SeniorExaminee> list = seniorExamineeDao.listSeniorExamineeExport(seniorSchoolId, seniorClassId,
				examCardNumber, confirmStatus);
		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
		// 定义宽度
		Map<Integer, Integer> colWidthList = new HashMap<Integer, Integer>();
		// 序号
		 int index = 0;
		for (SeniorExaminee as : list) {
			int i = 0;
			Map<String, Object> map = new LinkedHashMap<String, Object>();
			 seniorExportCellHandler(map,colWidthList,i++,"序号",++index);
			seniorExportCellHandler(map, colWidthList, i++, "准考证号", as.getExamCardNumber());
			seniorExportCellHandler(map, colWidthList, i++, "姓名", as.getStudentName());
			seniorExportCellHandler(map, colWidthList, i++, "性别", as.getGender());
			seniorExportCellHandler(map, colWidthList, i++, "出生年月", as.getBirthday());
			seniorExportCellHandler(map, colWidthList, i++, "民族", as.getNation());
			seniorExportCellHandler(map, colWidthList, i++, "籍贯", as.getNativePlace());
			seniorExportCellHandler(map, colWidthList, i++, "政治面貌", as.getPoliticalName());
			seniorExportCellHandler(map, colWidthList, i++, "考生类型", as.getStudentTypeName());
			seniorExportCellHandler(map, colWidthList, i++, "身份证号码", as.getIdCard());
			seniorExportCellHandler(map, colWidthList, i++, "联系电话1", as.getPhone1());
			seniorExportCellHandler(map, colWidthList, i++, "联系电话2", as.getPhone2());
			seniorExportCellHandler(map, colWidthList, i++, "户籍地区代码", as.getResidenceAreaCode());
			seniorExportCellHandler(map, colWidthList, i++, "户籍地址", as.getResidenceAreaCode());
			seniorExportCellHandler(map, colWidthList, i++, "学籍号", as.getStudentNumber());
			seniorExportCellHandler(map, colWidthList, i++, "建档号", as.getArchivesNumber());
			seniorExportCellHandler(map, colWidthList, i++, "班级代号",
					ConstantFactory.me().getSeniorSchoolClassById(as.getSeniorClassId()).getSeniorClassCode());
			seniorExportCellHandler(map, colWidthList, i++, "中学代号",
					ConstantFactory.me().getSeniorSchoolById(as.getSeniorSchoolId()).getSchoolCode());
			seniorExportCellHandler(map, colWidthList, i++, "中学名称",
					ConstantFactory.me().getSeniorSchoolById(as.getSeniorSchoolId()).getSchoolName());
			seniorExportCellHandler(map, colWidthList, i++, "是否已填报",
					as.getWriteStatus() == ExamineeStatusEnum.NOT_YET_WRITE.getValue()
							? ExamineeStatusEnum.NOT_YET_WRITE.getText() : ExamineeStatusEnum.ALREADY_WRITE.getText());
			seniorExportCellHandler(map, colWidthList, i++, "是否已确认",
					as.getConfirmStatus() == ExamineeStatusEnum.NOT_YET_CONFIRM.getValue()
							? ExamineeStatusEnum.NOT_YET_CONFIRM.getText()
							: ExamineeStatusEnum.ALREADY_CONFIRM.getText());
			// 提前批次（师范）
			seniorExportCellHandler(map, colWidthList, i++, "提前批次（师范）是否放弃",
					seniorWishFieldValueHandler(as.getSeniorWish(),"1",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "提前批次（师范）报考学校代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"1",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "提前批次（师范）报考学校名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"1",1,0,FieldTypeEnum.SCHOOL_NAME));
			// 指标生录取批次
//			seniorExportCellHandler(map, colWidthList, i++, "指标生录取批次是否放弃",
			seniorExportCellHandler(map, colWidthList, i++, "fqpc0zb",
					seniorWishFieldValueHandler(as.getSeniorWish(),"2",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "指标生录取一阶段报考学校代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"2",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "指标生录取一阶段报考学校名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"2",1,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "指标生录取二阶段报考学校A代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"13",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "指标生录取二阶段报考学校A名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"13",1,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "指标生录取二阶段报考学校B代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"13",2,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "指标生录取二阶段报考学校B名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"13",2,0,FieldTypeEnum.SCHOOL_NAME));
			// 提前录取（普高）
			seniorExportCellHandler(map, colWidthList, i++, "提前录取(普高)批次是否放弃",
					seniorWishFieldValueHandler(as.getSeniorWish(),"3",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "提前录取(普高)批次报考学校代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"3",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "提前录取(普高)批次报考学校名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"3",1,0,FieldTypeEnum.SCHOOL_NAME));
			// 第一批录取第一阶段(普高)
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取(普高、现代职教试点)批次是否放弃",
					seniorWishFieldValueHandler(as.getSeniorWish(),"4a5",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取一阶段（普高）报考学校A代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"4",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取一阶段（普高）报考学校A名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"4",1,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取一阶段（普高）报考学校B代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"4",2,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取一阶段（普高）报考学校B名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"4",2,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取一阶段（普高）报考学校C代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"4",3,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取一阶段（普高）报考学校C名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"4",3,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校A代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校A名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",1,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校A报考专业代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",1,1,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校A报考专业名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",1,1,FieldTypeEnum.MAJOR_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校B代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",2,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校B名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",2,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校B报考专业代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",2,1,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第一批录取二阶段（3+4）报考学校B报考专业名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"5",2,1,FieldTypeEnum.MAJOR_NAME));
			// 第二批录取(普高)
			seniorExportCellHandler(map, colWidthList, i++, "第二批录取(普高)批次是否放弃",
					seniorWishFieldValueHandler(as.getSeniorWish(),"6",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "第二批录取(普高)报考学校A代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"6",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第二批录取(普高)报考学校A名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"6",1,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第二批录取(普高)报考学校B代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"6",2,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第二批录取(普高)报考学校B名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"6",2,0,FieldTypeEnum.SCHOOL_NAME));
			// 第三批录取(普高)
			seniorExportCellHandler(map, colWidthList, i++, "第三批录取(普高)批次是否放弃",
					seniorWishFieldValueHandler(as.getSeniorWish(),"7",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "第三批录取(普高)报考学校代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"7",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第三批录取(普高)报考学校名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"7",1,0,FieldTypeEnum.SCHOOL_NAME));
			// 第四批录取(省部属)
			seniorExportCellHandler(map, colWidthList, i++, "fqpc4",
					seniorWishFieldValueHandler(as.getSeniorWish(),"8a9a10",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "YSXX20",
					seniorWishFieldValueHandler(as.getSeniorWish(),"8",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "YSZY201",
					seniorWishFieldValueHandler(as.getSeniorWish(),"8",1,1,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "YSZY202",
					seniorWishFieldValueHandler(as.getSeniorWish(),"8",1,2,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "YSFC20",
					seniorWishFieldValueHandler(as.getSeniorWish(),"8",1,0,FieldTypeEnum.MAJOR_ALLOCATE_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "YSFCQT",
					seniorWishFieldValueHandler(as.getSeniorWish(),"8",1,0,FieldTypeEnum.MAJOR_ALLOCATE_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "GZXX21",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY211",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",1,1,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY212",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",1,2,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY213",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",1,3,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY214",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",1,4,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY215",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",1,5,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZFC21",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",1,0,FieldTypeEnum.MAJOR_ALLOCATE_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "GZXX22",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",2,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY221",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",2,1,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY222",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",2,2,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY223",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",2,3,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY224",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",2,4,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY225",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",2,5,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZFC22",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",2,0,FieldTypeEnum.MAJOR_ALLOCATE_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "GZXX23",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",3,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY231",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",3,1,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY232",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",3,2,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY233",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",3,3,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY234",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",3,4,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZZY235",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",3,5,FieldTypeEnum.MAJOR_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "GZFC23",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",3,0,FieldTypeEnum.MAJOR_ALLOCATE_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "FCQTGZ",
					seniorWishFieldValueHandler(as.getSeniorWish(),"9",0,0,FieldTypeEnum.SCHOOL_ALLOCATE_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "ZZXX22",
					seniorWishFieldValueHandler(as.getSeniorWish(),"10",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "ZZZY221",
					seniorWishFieldValueHandler(as.getSeniorWish(),"10",1,1,FieldTypeEnum.MAJOR_CODE));
			// 第五批录取(市属高中、技工院校)
			seniorExportCellHandler(map, colWidthList, i++, "第五批录取(市属高中、技工院校)批次是否放弃",
					seniorWishFieldValueHandler(as.getSeniorWish(),"11",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "第五批录取(市属高中、技工院校)报考学校A代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"11",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第五批录取(市属高中、技工院校)报考学校A名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"11",1,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第五批录取(市属高中、技工院校)报考学校B代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"11",2,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第五批录取(市属高中、技工院校)报考学校B名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"11",2,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "第五批录取(市属高中、技工院校)报考学校C代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"11",3,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "第五批录取(市属高中、技工院校)报考学校C名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"11",3,0,FieldTypeEnum.SCHOOL_NAME));
			// 统配录取(市属高中、技工院校)
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)批次否放弃",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",0,0,FieldTypeEnum.QUIT_FLAG));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校A代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",1,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校A名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",1,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校B代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",2,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校B名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",2,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校C代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",3,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校C名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",3,0,FieldTypeEnum.SCHOOL_NAME));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校D代码",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",4,0,FieldTypeEnum.SCHOOL_CODE));
			seniorExportCellHandler(map, colWidthList, i++, "统配录取(市属高中、技工院校)报考学校D名称",
					seniorWishFieldValueHandler(as.getSeniorWish(),"12",4,0,FieldTypeEnum.SCHOOL_NAME));
			dataList.add(map);
		}
		// 创建excelWriter,使用xlsx,xls设置列宽有问题
		ExcelWriter excelWriter = new ExcelWriter(true);

		// 定义列宽
		for (int i = 0; i < colWidthList.entrySet().size(); i++) {
			excelWriter.getSheet().setColumnWidth(i, colWidthList.get(i) * 256);
		}
		// 生成文件名
		String fileName = "学生志愿信息表.xlsx";
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
		excelWriter.write(dataList);
		excelWriter.flush(response.getOutputStream());
		excelWriter.close();
	}

	/**
	 * 志愿导出列表单元格处理方法
	 *
	 * @param dataMap   保存到单元格中的数据
	 * @param widthMap  保存当前列最大宽度的map,key为第几列，value为宽度
	 * @param i         保存当前操作的是第几列
	 * @param fieldName 当前列的表头名
	 * @param value     保存的数据
	 * @author gaozhichang
	 * @date 2018-03-28 下午15:00
	 */
	private void seniorExportCellHandler(Map<String, Object> dataMap, Map<Integer, Integer> widthMap, int i,
										 String fieldName, Object value) throws UnsupportedEncodingException {
		dataMap.put(fieldName, value);
		// 当初始没有值时，传入字段名的长度
		if (widthMap.get(i) == null) {
			widthMap.put(i, fieldName.getBytes().length);
		}
		// 判断当前插入的数据宽度是否比之前的长，长则更新
		if (String.valueOf(value).getBytes().length > widthMap.get(i)) {
			widthMap.put(i, String.valueOf(value).getBytes().length);
		}
	}

	/**
	 * 用于区分导出数据类型的枚举
	 */
	private enum FieldTypeEnum {
		QUIT_FLAG(1),//退出标记
		SCHOOL_CODE(2),
		SCHOOL_NAME(3),
		MAJOR_CODE(4),
		MAJOR_NAME(5),
		SCHOOL_ALLOCATE_FLAG(6),
		MAJOR_ALLOCATE_FLAG(7);
		int type;

		FieldTypeEnum(int type) {
			this.type = type;
		}
	}

	/**
	 *志愿信息导出处理方法
	 *
	 * @param batchNum         批次编号
	 * @param schoolNum         学校编号
	 * @param majorNum         专业标号
	 * @author gaozhichang
	 * @date 2018-04-13 下午 4:12
	 */
	private String seniorWishFieldValueHandler(SeniorWish seniorWish, String batchNum, int schoolNum, int majorNum, FieldTypeEnum fieldType) {
		if (seniorWish == null) {
			return "--";
		}
		String result = "--";
		String schoolId = null;
		String majorId = null;
		switch (fieldType) {
			case QUIT_FLAG:
				Integer quitFlag = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "QuitFlag");
				result = quitFlag == null ? "--" : (quitFlag == 1 ? "是" : "否");
				break;
			case SCHOOL_CODE:
				schoolId = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "School" + schoolNum + "Id");
				if (StrUtil.isNotBlank(schoolId)) {
					result = ConstantFactory.me().getEnrollSchoolById(schoolId).getSchoolCode();
				}
				break;
			case SCHOOL_NAME:
				schoolId = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "School" + schoolNum + "Id");
				if (StrUtil.isNotBlank(schoolId)) {
					result = ConstantFactory.me().getEnrollSchoolById(schoolId).getSchoolName();
				}
				break;
			case MAJOR_CODE:
				schoolId = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "School" + schoolNum + "Id");
				majorId = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "School" + schoolNum + "Major" + majorNum + "Id");
				if (StrUtil.isNotBlank(schoolId) && StrUtil.isNotBlank(majorId)) {
					result = ConstantFactory.me().getEnrollSchoolById(schoolId).getSchoolCode()
							+ "-" + ConstantFactory.me().getEnrollMajorById(majorId).getMajorCode();
				}
				break;
			case MAJOR_NAME:
				majorId = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "School" + schoolNum + "Major" + majorNum + "Id");
				if (StrUtil.isNotBlank(majorId)) {
					result = ConstantFactory.me().getEnrollMajorById(majorId).getMajorName();
				}
				break;
			case SCHOOL_ALLOCATE_FLAG:
				Integer schoolAllocateFlag = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "SchoolAllocateFlag");
				result = schoolAllocateFlag == null ? "--" : (schoolAllocateFlag == 1 ? "是" : "否");
				break;
			case MAJOR_ALLOCATE_FLAG:
				Integer majorAllocateFlag = ReflectUtil.invoke(seniorWish, "getBatch" + batchNum + "School" + schoolNum + "MajorAllocateFlag");
				result = majorAllocateFlag == null ? "--" : (majorAllocateFlag == 1 ? "是" : "否");
				break;
			default:
				result = "--";
		}
		return result;
	}
}
